package GUIuse;

import GUIuse.mainuse.OrderManagementSystem;
import common.Product;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class ProductPanel extends JPanel {
    private OrderManagementSystem parent;
    private JTable productTable;
    private DefaultTableModel tableModel;
    private JButton addButton, editButton, deleteButton, refreshButton;
    
    public ProductPanel(OrderManagementSystem parent) {
        this.parent = parent;
        initialize();
    }
    
    private void initialize() {
        setLayout(new BorderLayout());
        
        // 创建表格模型和表格
        String[] columnNames = {"商品编号", "商品名称", "数量", "单价", "总价"};
        tableModel = new DefaultTableModel(columnNames, 0);
        productTable = new JTable(tableModel);
        productTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // 创建滚动面板
        JScrollPane scrollPane = new JScrollPane(productTable);
        add(scrollPane, BorderLayout.CENTER);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        
        addButton = new JButton("添加商品");
        editButton = new JButton("修改商品");
        deleteButton = new JButton("删除商品");
        refreshButton = new JButton("刷新");
        
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(refreshButton);
        
        add(buttonPanel, BorderLayout.NORTH);
        
        // 添加按钮事件监听
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAddProductDialog();
            }
        });
        
        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showEditProductDialog();
            }
        });
        
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteSelectedProduct();
            }
        });
        
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshTable();
            }
        });
        
        // 初始加载数据
        refreshTable();
    }
    
    // 刷新表格数据
    public void refreshTable() {
        tableModel.setRowCount(0); // 清空表格
        List<Product> products = parent.getProducts();
        for (Product product : products) {
            Object[] rowData = {
                product.getId(),
                product.getName(),
                product.getQuantity(),
                product.getUnitPrice(),
                product.getTotalPrice()
            };
            tableModel.addRow(rowData);
        }
    }
    
    // 显示添加商品对话框
    private void showAddProductDialog() {
        JDialog dialog = new JDialog((Frame) null, "添加商品", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(null);
        dialog.setLayout(new BorderLayout());
        
        JPanel panel = new JPanel(new GridLayout(5, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        // 创建输入字段
        JLabel idLabel = new JLabel("商品编号:");
        JTextField idField = new JTextField();
        
        JLabel nameLabel = new JLabel("商品名称:");
        JTextField nameField = new JTextField();
        
        JLabel quantityLabel = new JLabel("数量:");
        JTextField quantityField = new JTextField();
        
        JLabel unitPriceLabel = new JLabel("单价:");
        JTextField unitPriceField = new JTextField();
        
        // 总价字段（只读）
        JLabel totalPriceLabel = new JLabel("总价:");
        JTextField totalPriceField = new JTextField();
        totalPriceField.setEditable(false);
        totalPriceField.setBackground(Color.LIGHT_GRAY);
        
        panel.add(idLabel);
        panel.add(idField);
        panel.add(nameLabel);
        panel.add(nameField);
        panel.add(quantityLabel);
        panel.add(quantityField);
        panel.add(unitPriceLabel);
        panel.add(unitPriceField);
        panel.add(totalPriceLabel);
        panel.add(totalPriceField);
        
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        
        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 保存按钮事件
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    int id = Integer.parseInt(idField.getText());
                    String name = nameField.getText();
                    int quantity = Integer.parseInt(quantityField.getText());
                    double unitPrice = Double.parseDouble(unitPriceField.getText());
                    
                    if (name.isEmpty() || quantity <= 0 || unitPrice < 0) {
                        JOptionPane.showMessageDialog(dialog, "商品名称不能为空，数量必须大于0，单价不能小于0", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    
                    Product product = new Product(id, name, quantity, unitPrice);
                    
                    // 检查ID是否已存在
                    for (Product p : parent.getProducts()) {
                        if (p.getId() == id) {
                            JOptionPane.showMessageDialog(dialog, "商品编号已存在", "错误", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    }
                    
                    parent.addProduct(product);
                    refreshTable();
                    dialog.dispose();
                    JOptionPane.showMessageDialog(parent, "商品添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(dialog, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        
        // 取消按钮事件
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        
        // 添加数量和单价的事件监听，实时计算总价
        ActionListener calculateListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    int quantity = Integer.parseInt(quantityField.getText());
                    double unitPrice = Double.parseDouble(unitPriceField.getText());
                    double totalPrice = quantity * unitPrice;
                    totalPriceField.setText(String.format("%.2f", totalPrice));
                } catch (NumberFormatException ex) {
                    totalPriceField.setText("");
                }
            }
        };
        
        quantityField.addActionListener(calculateListener);
        unitPriceField.addActionListener(calculateListener);
        
        dialog.setVisible(true);
    }
    
    // 显示修改商品对话框
    private void showEditProductDialog() {
        int selectedRow = productTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要修改的商品", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        int id = (int) tableModel.getValueAt(selectedRow, 0);
        Product productToEdit = null;
        
        for (Product product : parent.getProducts()) {
            if (product.getId() == id) {
                productToEdit = product;
                break;
            }
        }
        
        if (productToEdit == null) {
            JOptionPane.showMessageDialog(this, "未找到选中的商品", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        JDialog dialog = new JDialog((Frame) null, "修改商品", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(null);
        dialog.setLayout(new BorderLayout());
        
        JPanel panel = new JPanel(new GridLayout(5, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        // 创建输入字段并填充当前值
        JLabel idLabel = new JLabel("商品编号:");
        JTextField idField = new JTextField(String.valueOf(productToEdit.getId()));
        idField.setEditable(false); // 商品编号不可修改
        
        JLabel nameLabel = new JLabel("商品名称:");
        JTextField nameField = new JTextField(productToEdit.getName());
        
        JLabel quantityLabel = new JLabel("数量:");
        JTextField quantityField = new JTextField(String.valueOf(productToEdit.getQuantity()));
        
        JLabel unitPriceLabel = new JLabel("单价:");
        JTextField unitPriceField = new JTextField(String.valueOf(productToEdit.getUnitPrice()));
        
        // 总价字段（只读）
        JLabel totalPriceLabel = new JLabel("总价:");
        JTextField totalPriceField = new JTextField(String.format("%.2f", productToEdit.getTotalPrice()));
        totalPriceField.setEditable(false);
        totalPriceField.setBackground(Color.LIGHT_GRAY);
        
        panel.add(idLabel);
        panel.add(idField);
        panel.add(nameLabel);
        panel.add(nameField);
        panel.add(quantityLabel);
        panel.add(quantityField);
        panel.add(unitPriceLabel);
        panel.add(unitPriceField);
        panel.add(totalPriceLabel);
        panel.add(totalPriceField);
        
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        
        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 保存按钮事件
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    String name = nameField.getText();
                    int quantity = Integer.parseInt(quantityField.getText());
                    double unitPrice = Double.parseDouble(unitPriceField.getText());
                    
                    if (name.isEmpty() || quantity <= 0 || unitPrice < 0) {
                        JOptionPane.showMessageDialog(dialog, "商品名称不能为空，数量必须大于0，单价不能小于0", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    
                    Product updatedProduct = new Product(id, name, quantity, unitPrice);
                    
                    parent.updateProduct(updatedProduct);
                    refreshTable();
                    dialog.dispose();
                    JOptionPane.showMessageDialog(parent, "商品修改成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(dialog, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        
        // 取消按钮事件
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        
        // 添加数量和单价的事件监听，实时计算总价
        ActionListener calculateListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    int quantity = Integer.parseInt(quantityField.getText());
                    double unitPrice = Double.parseDouble(unitPriceField.getText());
                    double totalPrice = quantity * unitPrice;
                    totalPriceField.setText(String.format("%.2f", totalPrice));
                } catch (NumberFormatException ex) {
                    totalPriceField.setText("");
                }
            }
        };
        
        quantityField.addActionListener(calculateListener);
        unitPriceField.addActionListener(calculateListener);
        
        dialog.setVisible(true);
    }
    
    // 删除选中的商品
    private void deleteSelectedProduct() {
        int selectedRow = productTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的商品", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        int id = (int) tableModel.getValueAt(selectedRow, 0);
        String name = (String) tableModel.getValueAt(selectedRow, 1);
        
        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除商品" + name + "吗？", "确认删除", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            parent.deleteProduct(id);
            refreshTable();
            JOptionPane.showMessageDialog(this, "商品删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
        }
    }
}